package cn.yaboya.user.service.impl;

import cn.yaboya.basic.exception.BusinessException;
import cn.yaboya.basic.service.Impl.BaseServiceImpl;
import cn.yaboya.basic.utils.Code;
import cn.yaboya.basic.utils.MD5Utils;
import cn.yaboya.basic.utils.StrUtils;
import cn.yaboya.user.domain.Logininfo;
import cn.yaboya.user.domain.User;
import cn.yaboya.user.mapper.LogininfoMapper;
import cn.yaboya.user.mapper.UserMapper;
import cn.yaboya.user.service.IUserService;
import cn.yaboya.basic.vo.RegisterVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author yaboya
 * @since 2022-07-04
 */
@Service
public class UserServiceImpl extends BaseServiceImpl<User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private LogininfoMapper logininfoMapper;


    @Override
    public User loadByPhone(String phone) {
        return userMapper.loadByPhone(phone);
    }


/**
* @Title: phoneCodeResister
* @Description: 用户点击注册执行方法
* @Author: LT
* @Version: 1.0
* @Date:  2022/7/6 16:45
* @Parameters: [registerVo]
* @Return void
*/
    public void phoneCodeResister(RegisterVo registerVo){
        Code.codeJudge(registerVo);

        // 2。判断是否注册过
        if (userMapper.loadByPhone(registerVo.getPhone()) != null) {
            throw new BusinessException("用户名已注册");
        }
        // 5.保存到user表 和logininfo 日志表
        User user = registerVo2User(registerVo);
        Logininfo logininfo = user2Logininfo(user);

        logininfoMapper.add(logininfo);
        user.setLogininfoId(logininfo.getId());
        userMapper.add(user);

    }



    /**
     * @Title: registerVo2User
     * @Description: 封装成一个user类
     * @Author: LT
     * @Version: 1.0
     * @Date:  2022/7/5 14:27
     * @Parameters: [registerVo]
     * @Return cn.yaboya.user.domain.User
     */
    public User registerVo2User(RegisterVo registerVo){
        User user = new User();
        // 设置手机号
        user.setPhone(registerVo.getPhone());
        // 把用户名设置成手机号
        user.setUsername(registerVo.getPhone());
        // 将密码使用md5进行加盐加密
        String salt = StrUtils.getComplexRandomString(32);
        String md5Pwd = MD5Utils.encrypByMd5(registerVo.getPassword() + salt);
        // 设置加盐加密的密码赋予
        user.setPassword(md5Pwd);
        user.setSalt(salt);
        return user;
    }

    /**
     * @Title: user2Logininfo
     * @Description: 设置logininfo对象数据
     * @Author: LT
     * @Version: 1.0
     * @Date:  2022/7/5 14:40
     * @Parameters: [user]
     * @Return cn.yaboya.user.domain.Logininfo
     */
    public Logininfo user2Logininfo(User user){
        // 利用工具类拷贝到Logininfo中
        Logininfo logininfo = new Logininfo();
        BeanUtils.copyProperties(user, logininfo);
        // 设置数据类型为用户
        logininfo.setType(1);
        return logininfo;
    }

}
